﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mail;
using MammothMicro.SMTPGuard;
using MammothMicro.SMTPGuard.Common;
using MammothMicro.SMTPGuard.Filter;
using MammothMicro.SmtpGuardFilter.Common;

namespace MammothMicro.SmtpGuardFilter.Filter
{
    /// <summary>
    /// Checks email against blocked keywords
    /// </summary>
    public class BlockedKeywordFilter:IEmailFilter
    {
        private List<string> _list = new List<string>();
        public bool Accept(MailMessage message)
        {
            if  (KeywordSearch(message.Body.ToLower()))
            {
                var msg = new SerializableMailMessage
                              {
                                  Email = message,
                                  Id = new Guid(),
                                  FilteredBy = Tools.Filters.BlockedKeywordFilter
                              };
                FilterManager.MailStore.Save(msg);
                return false;
            }
            return true ;
        }

        public void Reload()
        {
            var path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            path = path.Remove(0, 6) + @"\configuration\blockedkeywords.txt";
            var reader = new StreamReader(path);
            var text = reader.ReadToEnd().ToLower().ToLower();
            reader.Close();
            const string delimiter = "\r\n";
            var t = text.Split(delimiter.ToCharArray());
            _list = Tools.ClearEmptyItems(t.ToList());
            
        }

        private bool KeywordSearch(string data)
        {
            return _list.Any(data.Contains);
        }
    }
}


